package cn.cheneyjoo.config;

import cn.cheneyjoo.model.Configuration;
import cn.cheneyjoo.model.MappedStatement;
import cn.cheneyjoo.sqlsession.SqlSession;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.Locale;

public class MySqlSessionProxy implements InvocationHandler {
    private Configuration configuration;
    private SqlSession sqlSession;

    public MySqlSessionProxy(Configuration configuration,SqlSession sqlSession) {
        this.configuration = configuration;
        this.sqlSession=sqlSession;
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        // 方法名
        String methodName = method.getName();
        // 接口全限定名
        String className = method.getDeclaringClass().getName();
        // 唯一ID
        String statementId = className + "." + methodName;
        MappedStatement mappedStatement = configuration.getMappedStatementMap().get(statementId);
        if(mappedStatement!=null){
            String sqlType=mappedStatement.getSqlType();
            switch (sqlType.toLowerCase(Locale.ROOT)){
                case "select":
                    Type returnType = method.getGenericReturnType();
                    if (returnType instanceof ParameterizedType){
                        return sqlSession.selectList(statementId,args);
                    }
                    return sqlSession.selectOne(statementId,args);
                case "insert":
                    return sqlSession.insert(statementId,args);
                case "update":
                    return sqlSession.update(statementId,args);
                case "delete":
                    return sqlSession.delete(statementId,args);
                default:
                    throw  new RuntimeException("sql type error");
            }
        }
        return null;
    }
}
